<template>
  <div class="content-container">
    <!-- 动态题库头部 -->
    <TopicHeader :config="headerConfig" @button-click="handleHeaderAction" />

    <!-- 题目列表 -->
    <QuestionList :question-category-id="questionId" />
  </div>
</template>

<script setup name="QuestionBank">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import TopicHeader from '@/components/topic-header/index.vue'
import QuestionList from '@/components/question-list/index.vue'
import { getBankInfo } from './api'

import { bankInfoToHeaderConfig, getDefaultBankInfo, setPageTitle, handleHeaderButtonClick } from './service'

const route = useRoute()
const bankInfo = ref(null)

// 根据题库信息生成头部配置
const headerConfig = computed(() => {
  if (!bankInfo.value || !bankInfo.value.name) return null
  return bankInfoToHeaderConfig(bankInfo.value)
})

// 题目列表初始参数
const questionId = computed(() => route.params.bankId)

// 获取题库信息
const loadBankInfo = async () => {
  try {
    const bankId = route.params.bankId
    bankInfo.value = await getBankInfo(bankId)
    setPageTitle(bankInfo.value.title)
  } catch (error) {
    console.error('获取题库信息失败:', error)
    const defaultInfo = getDefaultBankInfo()
    bankInfo.value = defaultInfo
    setPageTitle(defaultInfo.title)
  }
}

const handleHeaderAction = (button) => {
  handleHeaderButtonClick(button.action)
}

onMounted(() => {
  loadBankInfo()
})

// 监听路由变化 在不同题库间切换
watch(
  () => route.params.id,
  () => {
    loadBankInfo()
  }
)
</script>

<style scoped>
.content-container {
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}
</style>
